package com.xmltest.demo.delete;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileOutputStream;

/**
 * @author xuehu
 * @date 2021/2/26 17:01
 */

public class Delete {

    /**
     * 1.前提条件
     * dom4j有一个办法可以快速的定位到我们想要删除的内容
     */
    public static void main(String[] args) {
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(new File("src/"));
            //1.获得根元素
            Element rootElement = document.getRootElement();

            //使用xpath找到我们需要的元素
            //定义xpath
            String xpath = "//student[@id='03']";
            Element student = (Element) document.selectSingleNode(xpath);
            //删除
            student.getParent().remove(student);
            //回写
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");
            XMLWriter writer = new XMLWriter(new FileOutputStream("src/students_copy.xml"), format);
            writer.write(document);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
